<template>
    <el-container class="home">
        <!-- 底部导航栏左侧系统名称 -->
        <el-aside width="auto" class="dt-aside">
            <div class="ub main-center cross-center dt-header-h dt-header-back1">
                <span class="ub" v-show="!isFlagTitle">
                    <img src="@/assets/images/syslogo.png" alt="logo" class="dt-header-img-logo">
                </span>
                <span v-show="!isFlagTitle" class="ub dt-header-font1" style="margin-left: 10px">
                    智慧平台管理端
                </span>
                <span v-show="isFlagTitle" class="ub dt-header-font1">
                    <img src="@/assets/images/syslogo.png" alt="logo" class="dt-header-img-logo">
                </span>
            </div>
            <!-- 左侧菜单栏 -->
            <menu-bar></menu-bar>
        </el-aside>
        <!-- 顶部导航栏右侧系统名称 -->
        <el-container>
            <el-header class="ub main-justify cross-center dt-header-h dt-header-back2 dt-header-font2">
                <div class="ub main-justify cross-center">
                    <div>
                        <i @click="openMenuFun" :class="[isCollapse ? 'el-icon-s-unfold' : ' el-icon-s-fold']" style="font-size: 20px"></i>
                    </div>
                    <div style="margin-left: 13px">
                        <el-breadcrumb separator="/">
                            <el-breadcrumb-item>
                                <span class="dt-header-font2">工作台</span>
                            </el-breadcrumb-item>
                            <el-breadcrumb-item v-for="(item, index) in breadList" :key="index">{{ item.title }}</el-breadcrumb-item>
                        </el-breadcrumb>
                    </div>
                </div>
                <!--右边工具栏-->
                <div class="ub main-justify cross-center">
                    <div>
                        <el-tooltip class="item" effect="dark" content="切为全屏" placement="bottom">
                            <i @click="handleFullScreen" class="fa fa-arrows-alt dt-header-icon-h"></i>
                        </el-tooltip>
                    </div>
                    <div>
                        <el-tooltip class="item" effect="dark" content="控制台" placement="bottom">
                            <i @click="homeFun" class="fa fa-television dt-header-icon-h"></i>
                        </el-tooltip>
                    </div>
                    <div>
                        <el-tooltip class="item" effect="dark" content="刷新" placement="bottom">
                            <i @click="reloadFun" class="fa fa-refresh dt-header-icon-h" aria-hidden="true"></i>
                        </el-tooltip>
                    </div>
                    <div>
                        <el-tooltip class="item" effect="dark" content="切换主题" placement="bottom">
                            <i @click="themeFun" class="fa fa-diamond dt-header-icon-h"></i>
                        </el-tooltip>
                    </div>
                    <img class="user-img" :src="userObject.avatar" alt="用户头像"/>
                    <el-dropdown>
                        <span class="user-name dt-header-font2">{{userObject.accountName}}</span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native="uploadFun('flagImg')"><i class="fa el-icon-upload"></i> 修改头像</el-dropdown-item>
                            <el-dropdown-item @click.native="updatePwdFun"><i class="fa el-icon-unlock"></i> 修改密码</el-dropdown-item>
                            <el-dropdown-item @click.native="logoutBtn"><i class="fa fa-sign-in"></i> 退出系统</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </el-header>
            <!-- 内容部分 -->
            <el-main class="dt-main">
                <!-- 选项卡封装 -->
                <tab></tab>
                <transition name="fade" mode="out-in">
                    <router-view></router-view>
                </transition>
            </el-main>
        </el-container>

        <!--系统修改密码弹框-->
        <el-dialog width="40%" title="修改密码" :visible.sync="pwdDialogVisible" :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form :rules="rules" ref="pwdForm" :model="pwdForm">
                <el-form-item prop="oldPassword" label="原密码" label-width="80px">
                    <el-input type="password" v-model="pwdForm.oldPassword" placeholder="请输入原密码"></el-input>
                </el-form-item>
                <el-form-item prop="newPassword" label="新密码" label-width="80px">
                    <el-input type="password" v-model="pwdForm.newPassword" placeholder="请输入新密码"></el-input>
                </el-form-item>
                <el-form-item prop="affirmPassword" label="确认密码" label-width="80px">
                    <el-input type="password" v-model="pwdForm.affirmPassword" placeholder="请确认密码"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                  <el-button @click="pwdDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="submitUpdatePwd()" :loading="loading.status" size="small">{{loading.status ? loading.SubText : loading.BtnText}}</el-button>
            </span>
        </el-dialog>

        <!--系统主题弹框-->
        <el-dialog
            title="系统主题"
            :visible.sync="centerDialogVisible"
            :modal="true"
            :modal-append-to-body="true"
            width="40%"
            center>
            <el-table
                :data="tableThemeData"
                border
                style="width: 100%">
                <el-table-column prop="name" label="主题名称" align="center" width="200">
                </el-table-column>
                <el-table-column prop="v" label="样式" align="center" width="200">
                </el-table-column>
                <el-table-column prop="enabled" label="是否启用" align="center">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.enabled"
                            :active-value="true"
                            :inactive-value="false"
                            @change="handleStatusChange(scope.row)"
                        ></el-switch>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 剪裁组件弹窗 -->
        <el-dialog
            title="上传头像"
            :visible.sync="cropperModel"
            width="850px">
            <cropper-image
                :Name="cropperName"
                @uploadImgSuccess = "handleUploadSuccess"
                ref="child">
            </cropper-image>
        </el-dialog>
    </el-container>
</template>

<script>
import MenuBar from '@/components/MenuBar'
import Tab from '@/components/Tab'
import { mapState } from "vuex"
import screenfull from "screenfull"
import Vue from "vue";
import CropperImage from "@/components/cropper/CropperImage";
export default {
    components: { MenuBar,Tab,CropperImage },
    inject: ['reload'],
    computed: {
        ...mapState({
            isCollapse: state => state.MenuStore.isCollapse,
            isFlagTitle: state => state.MenuStore.isFlagTitle
        })
    },
    data() {
        // 输入密码校验
        let validatePassword = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.pwdForm.newPassword) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
      return {
          isFullScreen: false,
          breadList: [],
          centerDialogVisible: false,
          tableThemeData: [],
          userObject: {
              id: null,
              accountName: null,
              avatar: null,
          },
          pwdDialogVisible: false,
          loading: {
              status: false,
              BtnText: '确 定',
              SubText: '提交中...'
          },
          // 密码表单
          pwdForm: {
              id: null,
              oldPassword: null,
              newPassword: null,
              affirmPassword: null
          },
          // 表单校验
          rules: {
              oldPassword: [
                  {required: true, message: '原密码不能为空', trigger: 'blur'},
                  {min: 6, max: 16, message: '长度在6到16个字符之间', trigger: 'blur'}
              ],
              newPassword: [
                  {required: true, message: '新密码不能为空', trigger: 'blur'},
                  {min: 6, max: 16, message: '长度在6到16个字符之间', trigger: 'blur'}
              ],
              affirmPassword: [
                  {validator: validatePassword, trigger: 'blur'},
                  {min: 6, max: 16, message: '长度在6到16个字符之间', trigger: 'blur'}
              ]
          },
          // 裁切图片参数
          cropperModel: false,
          cropperName: '',
      }
    },
    watch: {
        $route() {
            this.getBreadcrumb();
        },
    },
    created() {
        this.getBreadcrumb()
        this.getUser(Vue.ls.get('userId'))
    },
    methods: {
        // 获取用户信息
        getUser(userId) {
            this.$api.user.getById(userId).then(res =>{
                if(res.data.code === 2000){
                    this.userObject.id = res.data.data.id
                    this.userObject.accountName = res.data.data.accountName
                    if(res.data.data.avatar != null) {
                        this.userObject.avatar = res.data.data.avatar
                    }else {
                        this.userObject.avatar = 'https://i.gtimg.cn/club/item/face/img/2/16022_100.gif'
                    }
                }
            })
        },
        // 动态加载面包屑
        getBreadcrumb() {
            let cmsTitle = "CMS管理端"
            let matched = this.$route.matched
            let router = matched[1]
            if(router.name === 'desktop') {
                matched = [{title: cmsTitle}]
            }else {
                // 遍历循环当前激活的选项卡
                let activeTabs = this.$store.state.MenuStore.tabs
                activeTabs.forEach((tab) => {
                    if(router.name === tab.name) {
                        matched = [{title: cmsTitle},{title: tab.title}]
                    }
                })
            }
            this.breadList = matched
        },
        // 菜单收缩
        openMenuFun() {
            this.$store.commit("setOpenOrClose")
            this.$store.commit("setIsFlagTitle")
        },
        // 退出系统
        logoutFun() {
            this.$api.login.sysLogout().then(res =>{
                if(res.data.code === 2000){
                    localStorage.clear()
                    window.location.href ="/admin/login"
                }
            })
        },
        async logoutBtn() {
            await this.$api.user.addLogoutInfo().then(res => {
                if(res.data.code === 2000) {
                    this.logoutFun()
                }
            }).catch(err => {
                this.$message({type: "error", message: "系统异常"+err});
            })
        },
        // 刷新
        reloadFun() {
            this.reload()
        },
        // 控制台
        homeFun () {
            this.$router.push('/admin/home')
        },
        // 全屏
        handleFullScreen() {
            if (!screenfull.isEnabled) {
                this.$message.warning('抱歉，您的浏览器不支持全屏!')
                return false
            }else {
                screenfull.toggle()
                this.isFullScreen = true
            }
        },
        // 主题弹出框
        themeFun() {
            this.$api.init.queryThemeData().then(res => {
                if(res.data.code === 2000) {
                    this.tableThemeData = res.data.data
                    this.centerDialogVisible = true
                }
            })
        },
        // 启用主题设置
        handleStatusChange(row) {
            let text = row.enabled === true ? "启用" : "停用";
            this.$confirm('确认要"' + text + '""' + row.name + '"吗？', "系统提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: 'warning'
            }).then(() =>{
                this.$api.init.updateThemeEnabled(row.id).then(res => {
                    if(res.data.code === 2000){
                        this.$notify({
                            title: '系统提示',
                            message: '主题切换成功',
                            type: 'success'
                        });
                        this.centerDialogVisible = false
                        const loading = this.$loading({
                            lock: true,
                            text: '主题切换中......',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.9)'
                        });
                        setTimeout(() => {
                            loading.close();
                        }, 2000);
                        location.reload();
                    }else {
                        this.$message.error(res.data.msg)
                    }
                })
            }).catch(() => {
                this.$message.info("取消更新")
            });
        },
        // 修改密码弹框
        updatePwdFun() {
            this.resetForm("pwdFrom");
            this.pwdDialogVisible = true;
        },
        // 修改密码
        submitUpdatePwd() {
            let _this = this
            this.$refs.pwdForm.validate(valid => {
                if(valid){
                    this.loading.status = true
                    _this.pwdForm.id = Vue.ls.get('userId')
                    this.$api.user.updatePwd(this.pwdForm).then(res => {
                        if (res.data.code === 2000) {
                            _this.$alert('密码修改成功！请重新登录后', '系统提示', {
                                confirmButtonText: '确定',
                                type: 'success',
                                callback: res => {
                                    _this.loading.status = false
                                    localStorage.clear();
                                    window.location.href = "/";
                                }
                            });
                        }else{
                            this.$message.error(res.data.msg)
                            this.loading.status = false
                            return false
                        }
                    })
                }
            })
        },
        // 清空表单
        resetForm(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].resetFields();
            }
        },
        // 修改头像
        uploadFun(name) {
            this.cropperName = name;
            this.cropperModel = true;
        },
        // 图片上传成功回调
        handleUploadSuccess (data){
            this.cropperModel = false;
            // 更新用户头像
            this.userObject.avatar = data.url
            this.$api.user.updateAvatar(this.userObject).then(res => {
                if (res.data.code === 2000) {
                    this.$message.success(res.data.msg)
                }else{
                    this.$message.error(res.data.msg)
                    this.loading.status = false
                    return false
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>
.home {
    height: 100%;
}
.user-img {
    height: 25px;
    width: 25px;
    margin-right: 10px;
    border-radius: 50%;
}
.user-name {
    font-size: 13px;
    cursor: pointer;
}
// 左侧菜单
.menu-bar:not(.el-menu--collapse) {
    width: 200px;
    min-height: auto;
}
</style>
